package com.jsh.erp.ding;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.DepotHeadDing;
import com.jsh.erp.datasource.entities.DepotHeadDingExample;
import com.jsh.erp.datasource.mappers.DepotHeadDingMapper;
import com.jsh.erp.datasource.mappers.DepotHeadMapper;
import com.jsh.erp.service.depotHead.DepotHeadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ding")
public class DingEventPush {
    private Logger logger = LoggerFactory.getLogger(DingEventPush.class);
    @Resource private DepotHeadMapper depotHeadMapper;
    @Resource private DepotHeadDingMapper depotHeadDingMapper;
    @Resource private DepotHeadService depotHeadService;
    @Autowired private DingConfiguration dingConfiguration;
    @PostMapping("/register")
    public Map<String, String> callBack(
            @RequestParam(value = "msg_signature", required = false) String msg_signature,
            @RequestParam(value = "timestamp", required = false) String timeStamp,
            @RequestParam(value = "nonce", required = false) String nonce,
            @RequestBody(required = false) JSONObject json) {
        try {
            // 1. 从http请求中获取加解密参数

            // 2. 使用加解密类型
            // Constant.OWNER_KEY 说明：
            // 1、开发者后台配置的订阅事件为应用级事件推送，此时OWNER_KEY为应用的APP_KEY。
            // 2、调用订阅事件接口订阅的事件为企业级事件推送，
            //      此时OWNER_KEY为：企业的appkey（企业内部应用）或SUITE_KEY（三方应用）
            DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(
                    dingConfiguration.getToken(),
                    dingConfiguration.getEncodingAesKey(),
                    dingConfiguration.getCorpId());
            String encryptMsg = json.getString("encrypt");
            String decryptMsg = callbackCrypto.getDecryptMsg(msg_signature, timeStamp, nonce, encryptMsg);

            // 3. 反序列化回调事件json数据
            JSONObject eventJson = JSON.parseObject(decryptMsg);
            String eventType = eventJson.getString("EventType");

            // 4. 根据EventType分类处理
            if ("check_url".equals(eventType)) {
                // 测试回调url的正确性
                logger.info("测试回调url的正确性");
            } else if ("bpms_instance_change".equals(eventType)) {
                // 处理通讯录用户增加事件
                logger.info("发生了：" + eventType + "事件 : {}", eventJson.toString());
                this.handleInstanceChange(eventJson);
            } else {
                // 添加其他已注册的
                logger.info("发生了：" + eventType + "事件");
            }

            // 5. 返回success的加密数据
            Map<String, String> successMap = callbackCrypto.getEncryptedMap("success");
            return successMap;

        } catch (DingCallbackCrypto.DingTalkEncryptException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void handleInstanceChange(JSONObject eventJson){
        EventInstanceChange instanceChange = JSON.toJavaObject(eventJson,EventInstanceChange.class);
        String eventType = instanceChange.getEventType();
        String type = instanceChange.getType();
        String result = instanceChange.getResult();
        String staffId = instanceChange.getStaffId();

        //流程实例变更
        if ( eventType.equals("bpms_instance_change") && type.equals("finish")){
            DepotHeadDingExample depotHeadDingExample = new DepotHeadDingExample();
            depotHeadDingExample.createCriteria().andDingInstanceidEqualTo(instanceChange.getProcessInstanceId());
            List<DepotHeadDing> depotHeadDings = depotHeadDingMapper.selectByExample(depotHeadDingExample);
            DepotHeadDing depotHeadDing = null ;
            if ( depotHeadDings.size()>0 ){
                depotHeadDing = depotHeadDings.get(0);
                try {
                    String status = result.equals("agree") ? BusinessConstants.BILLS_STATUS_DING_AGREE :BusinessConstants.BILLS_STATUS_DING_REJECT;
                    depotHeadService.batchSetStatus(status,depotHeadDing.getDepotHeadId()+",");
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
